<template>
  <div class="app-container">

    <!--  -->
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">发布状态：</p>
      <el-select size="small" placeholder="请选择" clearable class="filter-item" style="width: 250px;margin-left:2%"
        v-model="listQuery.status">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button size="small" class="filter-item" type="success" icon="el-icon-search" style="margin-left:3%" @click="handleFilter">
        搜索
      </el-button>
      <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="list" size="small" border fit highlight-current-row style="width: 100%;margin-top:1%">
      <el-table-column type="index">
      </el-table-column>
      <el-table-column label="图标名称" width="300px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布地址" min-width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pubAddr=='firstPage'?'首页':scope.row.pubAddr=='marry'?'易婚庆':scope.row.pubAddr=='job'?'易就业':scope.row.pubAddr=='travel'?'易旅游':scope.row.pubAddr=='edu'?'易教育':scope.row.pubAddr=='special'?'易农特':scope.row.pubAddr=='science'?'易农科':scope.row.pubAddr=='handyService'?'生活服务':scope.row.pubAddr=='profit'?'轻松赚':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pubTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="展示位置" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.showChannel=='APPLETS'?'小程序':scope.row.showChannel=='CUSTOMER_APP'?'C端APP':scope.row.showChannel=='SHOP_KEEPER'?'掌柜APP':scope.row.showChannel=='OPERATE'?'运营管理平台':'' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="入口图标" width="200px" align="center">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.phoneNumber }}</span> -->
          <img :src="scope.row.imgUrl" style="width:100px;height:100px" alt="">
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status=='0'?'已下架':scope.row.status=='1'?'已发布':scope.row.status=='2'?'待发布':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button size="small" align="center" type="danger" v-if="row.status=='1' || row.status=='2' || row.status=='0'" @click="handleChange(row)">
            {{row.status=='1'?"下架":row.status=='2'?"发布":row.status=='0'?"发布":""}}
          </el-button>
          <el-button size="small" align="center" type="primary" v-if="row.status=='1' || row.status=='2'" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="small" align="center" type="primary" @click="handleExamine(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

      <!-- 弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
      append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 700px; margin-left:50px;">
        <el-form-item label="发布地址">
          <el-input v-model="temp.pubAddr" :disabled="true" />
        </el-form-item>
        <el-form-item label="入口名称：">
          <el-input v-model="temp.name" :disabled="dialogStatus == 'examine' ? true : false" />
        </el-form-item>
        <el-form-item label="展示位置">
          <el-select :disabled="dialogStatus == 'examine' ? true : false" size="small" placeholder="请选择" clearable
            class="filter-item" style="width: 250px;margin-left:2%" v-model="temp.showChannel">
            <el-option v-for="item in channelTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题图标：">
          <el-upload :disabled="dialogStatus == 'examine' ? true : false" class="avatar-uploader" action="http://10.0.0.123:10001/uploadImgUrl"
            :show-file-list="false" :on-success="handleAvatarSuccess" :http-request="customRequest">
            <img style="width:100px;height:100px" v-if="temp.imgUrl" :src="temp.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="icon关联内容：" hidden>
          <el-radio-group v-model="radio1" @change="guanlianDate">
            <el-radio :label="1">
              培训分类：
              <v-selectpage :disabled="dialogStatus == 'examine' ? true : false" :data="profession" key-field="id"
                v-model="temp.refId" show-field="name" style="width:250px;display:inline-block">
              </v-selectpage>
            </el-radio>
            <el-radio :label="2" style="margin-top:2%">
              培训机构：
              <v-selectpage :disabled="dialogStatus == 'examine' ? true : false" :data="sample" key-field="id" v-model="temp.refId"
                show-field="name" style="width:250px;display:inline-block">
              </v-selectpage>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联链接：">
          <el-input v-model="temp.linkUrl" :disabled="dialogStatus == 'examine' ? true : false" />
        </el-form-item>
        <el-form-item label="发布时间">
          <el-radio-group v-model="radio" @change="fabuDate" :disabled="dialogStatus == 'examine' ? true : false">
            <el-radio :label="1">即时发布</el-radio>
            <el-radio :label="2">定时发布：<el-date-picker v-model="temp.pubTime" type="datetime" placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" v-if="dialogStatus === 'create' || dialogStatus === 'update'" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // 异步请求 delLly
  import {
    getListPage,
    getEduCategoryList,
    getEduCompanyList,
    updateIcon,
    addIcon
  } from '@/api/IconManage'
  import Vue from 'vue'
  import {
    addImg
  } from '@/api/headWheel'
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination' // 分页插件
  import {
    SelectPage
  } from 'v-selectpage'

  const calendarTypeOptions = [{
      key: '0',
      display_name: '已下架'
    },
    {
      key: '1',
      display_name: '已发布'
    },
    {
      key: '2',
      display_name: '待发布'
    },
  ]
  const channelTypeOptions = [
    {
      key: 'SHOP_KEEPER',
      display_name: '掌柜APP'
    },
    {
      key: 'APPLETS',
      display_name: '小程序'
    },
    {
      key: 'CUSTOMER_APP',
      display_name: 'C端APP'
    },
    {
      key: 'OPERATE',
      display_name: '运营管理平台'
    }
  ]
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  const channelTypeKeyValue = channelTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    inject: ["reload"],
    components: {
      Pagination,
      'v-selectpage': SelectPage
    },

    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
      channelTypeFilter(type) {
        return channelTypeKeyValue[type]
      }
    },
    data() {
      return {
        radio1: 0,
        radio: 1,
        sample: [],
        profession: [],
        channelTypeOptions,
        deptValue: '',
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 10,
          sort: '+id',
          status: ''
        },
        deps: [],
        sortOptions: [{
          label: 'ID Ascending',
          key: '+id'
        }, {
          label: 'ID Descending',
          key: '-id'
        }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          imgUrl: '',
          pubAddr: 'firstPage'
        },
        dialogFormVisible: false,
        calendarTypeOptions,
        dialogStatus: '',
        textMap: {
          update: '查看详情',
          create: '添加',
          examine: '查看详情'
        },
        rowId: "",
        dialogPvVisible: false,
        outerVisible: false,
        pvData: [],
        rules: {
          type: [{
            required: true,
            message: 'type is required',
            trigger: 'change'
          }],
          timestamp: [{
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }],
          title: [{
            required: true,
            message: 'title is required',
            trigger: 'blur'
          }]
        },
        downloadLoading: false,
        liaUser: null,
        ids: [],
        select: null,
        allInfo: []
      }
    },
    created() {
      this.getList()
    },
    methods: {
      fabuDate() {
        console.log(this.radio)
        if (this.radio === 1) {
          this.temp.pubTime = ''
        } else if (this.radio === 2) {
          return this.temp.pubTime
        }
      },
      guanlianDate() {
        if (this.radio1 === 1) {
          this.temp.refType = 'eduCatId'
        } else if (this.radio1 === 2) {
          this.temp.refType = 'eduComId'
        }
      },
      handleAvatarSuccess(res, file) {
        this.temp.imgUrl = URL.createObjectURL(file.raw)
      },
      customRequest(data) {
        const formData = new FormData()
        formData.append('file', data.file)
        this.saveFile(formData)
      },
      saveFile(formData) {
        addImg(formData).then(res => {
          // this.imageUrl=res.data
          this.temp.imgUrl = res.data.filePath
          this.$notify({
            title: '上传成功',
            type: 'success',
            duration: 2500
          })
        })
      },

      // 获取分类列表
      getEduCategoryList() {
        getEduCategoryList().then(res => {
          this.profession = res.data
        })
      },
      // 获取培训公司列表
      getEduCompanyList() {
        getEduCompanyList().then(res => {
          this.sample = res.data
          console.log(this.sample)
        })
      },
      getList() {
        this.listLoading = true
        var params = {
          // pageConvert: true,
          pageNum: this.listQuery.pageNum - 1,
          pageSize: this.listQuery.pageSize,
          // realName:this.listQuery.realName,
          // phoneNumber:this.listQuery.phoneNumber
          status: this.listQuery.status,
          pubAddr: 'firstPage'
        }
        getListPage(params).then(response => {
          this.list = response.data.content
          console.log(this.list)
          this.total = response.data.totalElements
          console.log(this.total)
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 800)
        })
      },
      handleFilter() {
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const {
          prop,
          order
        } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined
        }
      },
      handleExamine(row) {
        this.dialogStatus = 'examine'
        this.dialogFormVisible = true
        this.temp = Object.assign({}, row)
      },
      handleUpdate(row) {
        this.getEduCompanyList()
        this.getEduCategoryList()
        if (this.temp.refType == 'eduCatId') {
          this.radio1 = 1
        } else if (this.temp.refType == 'eduComId') {
          this.radio1 = 2
        }
        this.temp = Object.assign({}, row) // copy obj
        // this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        if (this.radio === 1) {
          this.temp.pubTime = ''
        } else if (this.radio === 2) {
          var aa = this.temp.pubTime.trim().split(/\s+/)
          this.temp.pubTime = aa[0] + 'T' + aa[1]
        }
        // console.log(this.temp.pubTime)
        const tempData = Object.assign({}, this.temp)
        // console.log(tempData)
        updateIcon(tempData).then(() => {
          for (const v of this.list) {
            if (v.id === this.temp.id) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, this.temp)
              break
            }
          }
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      },
      handleChange(row) {
        this.temp = Object.assign({}, row)
        if (this.temp.status == '2') {
          this.temp.status = '1'
        } else if (this.temp.status == '1') {
          this.temp.status = '0'
        } else if (this.temp.status == '0') {
          this.temp.status = '1'
        }
        this.updateData()
      },
      handleCreate() {
        this.resetTemp()
        this.getEduCompanyList()
        this.getEduCategoryList()
        this.dialogStatus = 'create'
        this.temp.pubAddr = 'firstPage'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        if (this.radio === 1) {
          this.temp.pubTime = ''
        } else if (this.radio === 2) {
          var aa = this.temp.pubTime.trim().split(/\s+/)
          this.temp.pubTime = aa[0] + 'T' + aa[1]
        }
        addIcon(this.temp).then(() => {
          this.list.unshift(this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '添加成功',
            type: 'success',
            duration: 2000
          })
          this.reload()
        })

      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ?
          'ascending' :
          sort === `-${key}` ?
          'descending' :
          ''
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
